
type ICallback = (arg?: unknown) => unknown

type ICallbacks = ICallback[]

interface IEvents {
  [key: string]: ICallbacks
}

function createEmitter() {
  const events:IEvents  = {

  }

  return {
    // 绑定自定义事件
    on(eventName: string, callback:ICallback) {
      if (events[eventName]) {
        events[eventName].push(callback)
      }else {
        events[eventName] = [callback]
      }
    },
    // 解绑自定义事件
    off(eventName: string, callback?: ICallback) {
      /*
       * off('eventName')解绑该事件(eventName)的所以回调
       * off('eventName', cb)解绑该事件(eventName)的一个回调(cb)
       * */
      const callbacks = events[eventName]
      if (!callback) {
        return
      }
      if (callback) {
        // 解绑一个
        // 比较函数是否相同，比较的地址值
        events[eventName] = callbacks.filter(cb => cb !== callback)
      } else {
        // 解绑所有
        delete events[eventName]
      }
    },
    // 触发自定义事件
    emit(eventName: string, arg?: unknown) {
      const callbacks = events[eventName]
      if (!callbacks) {
        return
      }
      // 遍历所以函数
      callbacks.forEach(item => item(arg))
    }
  }

}

const globalEmitter = createEmitter()

export default globalEmitter